<template>
  <div class="writing-page">
    <!-- 模式选择 -->
    <div class="mode-selector">
      <h2>选择写作模式</h2>
      <el-radio-group v-model="writingStore.currentMode" @change="handleModeChange" size="large">
        <el-radio-button value="biography">传记模式</el-radio-button>
        <el-radio-button value="diary">日记模式</el-radio-button>
        <el-radio-button value="memoir">回忆录模式</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 写作区域 -->
    <el-row :gutter="20" class="writing-area">
      <!-- 左侧：输入区域 -->
      <el-col :span="16">
        <el-card class="input-card">
          <template #header>
            <div class="card-header">
              <span>{{ getModeTitle() }}</span>
              <div class="header-actions">
                <el-button size="small" @click="showAiDialog = true" type="primary">
                  <el-icon><ChatDotRound /></el-icon>
                  AI助手
                </el-button>
                <el-button size="small" @click="handleSpeechInput">
                  <el-icon><Microphone /></el-icon>
                  语音输入
                </el-button>
                <el-button size="small" @click="handleImageUpload">
                  <el-icon><Picture /></el-icon>
                  图片识别
                </el-button>
                <el-button size="small" @click="handleAudioUpload">
                  <el-icon><VideoCamera /></el-icon>
                  音频上传
                </el-button>
              </div>
            </div>
          </template>
          
          <!-- 文本输入区域 -->
          <el-input
            v-model="writingStore.content"
            type="textarea"
            :rows="20"
            :placeholder="getPlaceholder()"
            class="content-input"
          />
          
          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button @click="handleTextToSpeech" :disabled="!writingStore.content">
              <el-icon><VideoPlay /></el-icon>
              朗读内容
            </el-button>
            <el-button @click="handleSaveBookmark" :disabled="!writingStore.content">
              <el-icon><Star /></el-icon>
              保存书签
            </el-button>
            <el-button @click="handleSaveDraft" :disabled="!writingStore.content">
              <el-icon><Document /></el-icon>
              保存草稿
            </el-button>
            <el-button @click="handleExport" :disabled="!writingStore.content">
              <el-icon><Download /></el-icon>
              导出内容
            </el-button>
            <el-button @click="handleClear" :disabled="!writingStore.content" type="danger">
              <el-icon><Delete /></el-icon>
              清空内容
            </el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：AI建议和预览 -->
      <el-col :span="8">
        <!-- AI建议问题 -->
        <el-card class="suggestions-card">
          <template #header>
            <span>AI写作建议</span>
          </template>
          <div class="suggestions">
            <h4>建议问题：</h4>
            <div 
              v-for="(question, index) in currentSuggestions" 
              :key="index"
              class="suggestion-item"
              @click="handleQuestionClick(question)"
            >
              <el-icon><QuestionFilled /></el-icon>
              <span>{{ question }}</span>
            </div>
          </div>
        </el-card>

        <!-- 内容预览 -->
        <el-card class="preview-card" v-if="writingStore.content">
          <template #header>
            <span>实时预览</span>
          </template>
          <div class="preview-content" v-html="formattedContent"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- AI对话框 -->
    <el-dialog v-model="showAiDialog" title="AI写作助手" width="600px">
      <div class="ai-chat">
        <div class="chat-messages">
          <div 
            v-for="(message, index) in chatMessages" 
            :key="index"
            :class="['message', message.type]"
          >
            <div class="message-content">{{ message.content }}</div>
          </div>
        </div>
        <div class="chat-input">
          <el-input
            v-model="chatInput"
            placeholder="向AI描述您想要写的内容..."
            @keyup.enter="sendChatMessage"
          >
            <template #append>
              <el-button @click="sendChatMessage" type="primary">发送</el-button>
            </template>
          </el-input>
        </div>
      </div>
    </el-dialog>

    <!-- 书签保存对话框 -->
    <el-dialog v-model="showBookmarkDialog" title="保存书签" width="400px">
      <el-form>
        <el-form-item label="书签标题">
          <el-input v-model="bookmarkTitle" placeholder="请输入书签标题" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showBookmarkDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmSaveBookmark">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文件上传（隐藏） -->
    <input
      ref="imageUpload"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleImageFileChange"
    />
    <input
      ref="audioUpload"
      type="file"
      accept="audio/*"
      style="display: none"
      @change="handleAudioFileChange"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useWritingStore } from '@/stores/writing'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'

const writingStore = useWritingStore()
const authStore = useAuthStore()

const showAiDialog = ref(false)
const showBookmarkDialog = ref(false)
const bookmarkTitle = ref('')
const chatInput = ref('')
const chatMessages = ref([])
const imageUpload = ref()
const audioUpload = ref()

const currentSuggestions = computed(() => {
  return writingStore.suggestedQuestions[writingStore.currentMode] || []
})

const formattedContent = computed(() => {
  return writingStore.content.replace(/\n/g, '<br>')
})

const getModeTitle = () => {
  const titles = {
    biography: '传记写作',
    diary: '日记记录',
    memoir: '回忆录写作'
  }
  return titles[writingStore.currentMode]
}

const getPlaceholder = () => {
  const placeholders = {
    biography: '开始记录您的人生故事...\n您可以从童年开始写起，或者从某个重要的人生节点开始。',
    diary: '记录今天发生的事情...\n您可以写下今天的感受、见闻或者思考。',
    memoir: '回忆那些珍贵的时光...\n选择一段特殊的回忆，详细记录当时的情景和感受。'
  }
  return placeholders[writingStore.currentMode]
}

const handleModeChange = () => {
  ElMessage.info(`已切换到${getModeTitle()}模式`)
}

const handleQuestionClick = (question) => {
  writingStore.updateContent(writingStore.content + '\n\n' + question + '\n')
  ElMessage.success('问题已添加到内容中')
}

const handleSpeechInput = () => {
  if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
    const recognition = new SpeechRecognition()
    
    recognition.lang = 'zh-CN'
    recognition.continuous = true
    recognition.interimResults = false
    
    recognition.onresult = (event) => {
      let transcript = ''
      for (let i = event.resultIndex; i < event.results.length; i++) {
        transcript += event.results[i][0].transcript
      }
      writingStore.updateContent(writingStore.content + transcript)
      ElMessage.success('语音识别完成')
    }
    
    recognition.onerror = () => {
      ElMessage.error('语音识别失败，请重试')
    }
    
    recognition.start()
    ElMessage.info('正在进行语音识别，请开始说话...')
  } else {
    ElMessage.error('您的浏览器不支持语音识别功能')
  }
}

const handleImageUpload = () => {
  imageUpload.value.click()
}

const handleImageFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 模拟图片识别
    setTimeout(() => {
      const mockText = `[从图片识别出的文字：这是一张${file.name}的图片，包含了一些有意义的内容...]`
      writingStore.updateContent(writingStore.content + '\n\n' + mockText)
      ElMessage.success('图片识别完成')
    }, 1000)
    ElMessage.info('正在识别图片内容...')
  }
}

const handleAudioUpload = () => {
  audioUpload.value.click()
}

const handleAudioFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 模拟音频转文字
    setTimeout(() => {
      const mockText = `[从音频文件 ${file.name} 转换的文字：这里是从音频中识别出的内容...]`
      writingStore.updateContent(writingStore.content + '\n\n' + mockText)
      ElMessage.success('音频转换完成')
    }, 2000)
    ElMessage.info('正在转换音频为文字...')
  }
}

const handleTextToSpeech = () => {
  if ('speechSynthesis' in window) {
    const utterance = new SpeechSynthesisUtterance(writingStore.content)
    utterance.lang = 'zh-CN'
    utterance.rate = 0.8
    window.speechSynthesis.speak(utterance)
    ElMessage.success('开始朗读内容')
  } else {
    ElMessage.error('您的浏览器不支持语音合成功能')
  }
}

const handleSaveBookmark = () => {
  if (!authStore.isLoggedIn) {
    ElMessage.warning('请先登录后再保存书签')
    return
  }
  bookmarkTitle.value = `${getModeTitle()} - ${new Date().toLocaleDateString()}`
  showBookmarkDialog.value = true
}

const confirmSaveBookmark = () => {
  if (!bookmarkTitle.value.trim()) {
    ElMessage.warning('请输入书签标题')
    return
  }
  
  writingStore.addBookmark({
    title: bookmarkTitle.value,
    content: writingStore.content
  })
  
  showBookmarkDialog.value = false
  bookmarkTitle.value = ''
  ElMessage.success('书签保存成功')
}

const handleSaveDraft = () => {
  if (!authStore.isLoggedIn) {
    ElMessage.warning('请先登录后再保存草稿')
    return
  }
  
  writingStore.saveDraft()
  ElMessage.success('草稿保存成功')
}

const handleExport = () => {
  const blob = new Blob([writingStore.content], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${getModeTitle()}-${new Date().toLocaleDateString()}.txt`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('内容导出成功')
}

const handleClear = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有内容吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    writingStore.clearContent()
    ElMessage.success('内容已清空')
  } catch {
    // 用户取消
  }
}

const sendChatMessage = () => {
  if (!chatInput.value.trim()) return
  
  chatMessages.value.push({
    type: 'user',
    content: chatInput.value
  })
  
  // 模拟AI回复
  setTimeout(() => {
    const aiResponses = [
      '这是一个很有趣的话题，您可以从以下几个角度来展开...',
      '根据您的描述，我建议您可以添加一些具体的细节和感受...',
      '这段经历很有价值，您可以描述一下当时的环境和心情...',
      '建议您可以按照时间顺序来组织这部分内容...'
    ]
    const randomResponse = aiResponses[Math.floor(Math.random() * aiResponses.length)]
    
    chatMessages.value.push({
      type: 'ai',
      content: randomResponse
    })
  }, 1000)
  
  chatInput.value = ''
}

onMounted(() => {
  // 初始化时的欢迎消息
  if (chatMessages.value.length === 0) {
    chatMessages.value.push({
      type: 'ai',
      content: '您好！我是您的AI写作助手，有什么可以帮助您的吗？'
    })
  }
})
</script>

<style scoped>
.writing-page {
  max-width: 1400px;
  margin: 0 auto;
}

.mode-selector {
  text-align: center;
  margin-bottom: 20px;
}

.mode-selector h2 {
  margin-bottom: 15px;
  color: #333;
}

.writing-area {
  margin-top: 20px;
}

.input-card, .suggestions-card, .preview-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.content-input {
  margin-bottom: 15px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.suggestions {
  margin-top: 10px;
}

.suggestion-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  margin: 5px 0;
  background: #f8f9fa;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.suggestion-item:hover {
  background: #e9ecef;
}

.preview-content {
  max-height: 400px;
  overflow-y: auto;
  line-height: 1.6;
  color: #333;
}

.ai-chat {
  height: 400px;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  margin-bottom: 15px;
}

.message {
  margin-bottom: 15px;
}

.message.user .message-content {
  background: #409eff;
  color: white;
  padding: 10px;
  border-radius: 18px;
  margin-left: 20%;
  text-align: right;
}

.message.ai .message-content {
  background: #f0f2f5;
  color: #333;
  padding: 10px;
  border-radius: 18px;
  margin-right: 20%;
}

.chat-input {
  margin-top: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
